Data Grid

Conditionally Format DataGrid Column Text

Description
This customization shows how to set the color of a DataGrid cell based on its value.
Variables
Table Name
Select a database table to be shown in DataGrid
Applies to
Page class
Code
      
''' 
''' This method is called when a page is loaded. This method will
''' Populate the DataGrid.
''' 
''' The object that raised the load event.
''' The object that contains the event data of the load event.
Private Sub MyPageLoad(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
    If Not (Me.IsPostBack) Then 
        Dim myDataGrid As System.Web.UI.WebControls.DataGrid = CType(Me.FindControlRecursively("myDataGrid"), System.Web.UI.WebControls.DataGrid)
        
         ' If DataGrid is found then populate it.
        If (Not myDataGrid Is Nothing) Then
            ' example of where clause is
            ' whereStr = " myNumericField = 1"
            ' whereStr = " myStrField = '1'"
            Dim whereStr as String = Nothing

            ' Create orderBy clause
            Dim ob As BaseClasses.Data.OrderBy = Nothing

            ' Set page index and size
            Dim pageIndex as Integer = 0
            Dim pageSize as Integer = 1000

            ' Retrieving first 1000 records.       
            ' Bind the result set to the DataGrid.        
            myDataGrid.DataSource = ${${Table Name}ClassName}.GetDataTable(whereStr, ob, pageIndex, pageSize)
            myDataGrid.DataBind         
        End If
    End If 
End Sub
 
Applies to
Page class
Code
 
''' 
''' This method is called when DataGrid items databind.
''' Set the OnItemDataBound property of the datagrid to have a value of "MyItemDataBound"
''' This function is called everytime an item is bound to the datagrid
''' 
''' The object that raised the load event.
''' The object that contains the event data of the DataGrid items.
Public Sub MyItemDataBound(ByVal sender As Object, _
    ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) 
    If e.Item.ItemType = ListItemType.Item OrElse _
        e.Item.ItemType = ListItemType.AlternatingItem Then 
        
        ' Check for all cells in the DataGrid.
        Dim i As Integer = 0 
        While i < (e.Item.Cells.Count) 
        
            ' Customize the business logic here.
            If e.Item.Cells(i).Text = "myValue" Then 

                ' If cell contains text "myValue", then
                ' set the cell's back color to yellow.                
                e.Item.Cells(i).BackColor = System.Drawing.Color.Yellow                 
            End If 
            System.Math.Min(System.Threading.Interlocked.Increment(i),i-1) 
        End While 
    End If     
End Sub
     

Terms of Service Privacy Statement